import React, { useEffect, useState, useRef, useCallback } from 'react';
import { Card, Image, Tag, Typography, Form, Input, Button, Spin, message } from 'antd';
import { CalendarOutlined, PlayCircleOutlined, TagsOutlined, FileTextOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { getVarietyShowInfoPage, VarietyShowInfoDetail } from '@/services/VarietyShowInfo';
import { famousPersonId } from '@/services';
import styles from './index.less';

const { Title, Text } = Typography;

const Variety: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<VarietyShowInfoDetail[]>([]);
  const [total, setTotal] = useState(0);
  const [form] = Form.useForm();
  const [hasMore, setHasMore] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const containerRef = useRef<HTMLDivElement>(null);
  const loadingRef = useRef(false);

  const fetchData = async (values: any = {}, page = 1, isLoadMore = false) => {
    if (loadingRef.current) return;
    loadingRef.current = true;
    try {
      setLoading(true);
      const pageSize = 9;
      const response = await getVarietyShowInfoPage({
        pageCurrent: page,
        pageSize,
        famousPersonId,
        ...values
      });
      
      if (isLoadMore) {
        setData(prev => [...prev, ...response.list]);
      } else {
        setData(response.list || []);
      }
      
      setTotal(response.totalCount || 0);
      setHasMore(response.totalCount > page * pageSize);
      setCurrentPage(page);
    } catch (error) {
      message.error('获取综艺列表失败');
    } finally {
      setLoading(false);
      loadingRef.current = false;
    }
  };

  const handleScroll = useCallback(() => {
    if (!containerRef.current || loading || !hasMore || loadingRef.current) return;

    const container = containerRef.current;
    const { scrollTop, clientHeight, scrollHeight } = container;
    const scrollThreshold = 100; // 滚动阈值

    if (scrollHeight - scrollTop - clientHeight < scrollThreshold) {
      const values = form.getFieldsValue();
      fetchData(values, currentPage + 1, true);
    }
  }, [loading, hasMore, currentPage, form]);

  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
      return () => container.removeEventListener('scroll', handleScroll);
    }
  }, [handleScroll]);

  useEffect(() => {
    fetchData();
  }, []);

  const handleSearch = async (values: any) => {
    setCurrentPage(1);
    setHasMore(true);
    await fetchData(values, 1);
  };

  const handleReset = () => {
    form.resetFields();
    setCurrentPage(1);
    setHasMore(true);
    fetchData();
  };

  const handleCardClick = (id: number) => {
    history.push(`/works/variety/${btoa(id.toString())}`);
  };

  return (
    <div className={styles.varietyListContent}>
      <div className={styles.searchSection}>
        <Form
          form={form}
          onFinish={handleSearch}
          className={styles.searchForm}
        >
          <Form.Item name="keyword">
            <Input
              placeholder="搜索综艺名称、期数名称..."
              allowClear
              size="middle"
            />
          </Form.Item>
          <div className="button-group">
            <Button type="primary" htmlType="submit" size="middle">搜索</Button>
            <Button onClick={handleReset} size="middle">重置</Button>
          </div>
        </Form>
        <div className={styles.searchResult}>
          找到 <Text strong>{total}</Text> 个综艺作品
        </div>
      </div>

      <div className={styles.varietyListWrapper} ref={containerRef}>
        <div className={styles.varietyList}>
          {data.map((item) => (
            <Card
              key={item.id}
              className={styles.varietyCard}
              onClick={() => item.id && handleCardClick(item.id)}
            >
              <div className={styles.posterWrapper}>
                <Image
                  src={`/api/file/play/${item.poster}`}
                  alt={item.title}
                  className={styles.poster}
                  preview={false}
                  fallback="/images/default-cover.png"
                />
              </div>
              <div className={styles.contentWrapper}>
                <div className={styles.header}>
                  <Title level={5} className={styles.title}>{item.title}</Title>
                  <Tag color="blue">{item.periodName}</Tag>
                </div>
                <div className={styles.infoList}>
                  <div className={styles.infoItem}>
                    <CalendarOutlined className={styles.icon} />
                    <span className={styles.label}>播出时间:</span>
                    <span className={styles.value}>{item.releaseDate || '未知'}</span>
                  </div>

                  <div className={styles.infoItem}>
                    <PlayCircleOutlined className={styles.icon} />
                    <span className={styles.label}>期数:</span>
                    <span className={styles.value}>第{item.period || 0}/{item.sumPeriod || 0}期</span>
                  </div>

                  {item.tags && (
                    <div className={styles.infoItem}>
                      <TagsOutlined className={styles.icon} />
                      <span className={styles.label}>类型:</span>
                      <span className={styles.value}>
                        {item.tags.split(/[,，、]/g).map((tag, index) => (
                          <Tag key={index} color="blue">{tag.trim()}</Tag>
                        ))}
                      </span>
                    </div>
                  )}

                  {item.description && (
                    <div className={styles.infoItem}>
                      <FileTextOutlined className={styles.icon} />
                      <span className={styles.label}>简介:</span>
                      <span className={styles.value}>
                        <span className={styles.description}>{item.description}</span>
                      </span>
                    </div>
                  )}
                </div>
              </div>
            </Card>
          ))}
        </div>
        
        {loading && (
          <div className={styles.loadingMore}>
            <Spin />
            <span>加载中...</span>
          </div>
        )}
        
        {!hasMore && data.length > 0 && (
          <div className={styles.noMore}>
            没有更多数据了
          </div>
        )}
      </div>
    </div>
  );
};

export default Variety; 